#include <iostream>
#include <vector>

using namespace std;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if (head == nullptr || head->next == nullptr) {
            return true;
        }
        ListNode* tail = head;
        while (tail->next->next != nullptr)
            tail = tail->next;
        if (head->val != tail -> next -> val) return false;
        return dup(head, tail);
    }

    bool dup(ListNode* head, ListNode* btail) {
        if (head == btail && head -> val == head -> next -> val) {
            return true;
        }
        if (head == btail->next) {
            return true;
        }
        if (head->val != btail -> next -> val)
            return false;
        ListNode* tail = head;
        while(tail->next != btail)
            tail = tail -> next;
        return dup(head->next, tail);
    }
};

ListNode* vectorToListNode(vector<int> &list) {
    ListNode* dummyRoot = new ListNode(0);
    ListNode* ptr = dummyRoot;
    for (int item: list) {
        ptr->next = new ListNode(item);
        ptr = ptr ->next;
    }
    ptr = dummyRoot->next;
    delete dummyRoot;
    return ptr;
}

int main() {
    vector<int> l1{1, 1, 2, 1};
    ListNode* node = vectorToListNode(l1);
    bool ret = Solution().isPalindrome(node);
    cout << "res: " << ret << endl;
}